package com.example.aitasks.service;

import com.example.aitasks.config.AiProps;
import okhttp3.*;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class AiService {
    private final AiProps aiProps;
    private final OkHttpClient client;
    private final ObjectMapper mapper = new ObjectMapper();

    public AiService(AiProps aiProps) {
        this.aiProps = aiProps;
        this.client = new OkHttpClient.Builder()
                .callTimeout(Duration.ofSeconds(aiProps.getTimeoutSeconds() != null ? aiProps.getTimeoutSeconds() : 60))
                .build();
    }

    public String summarizeToJson(String model, String system, String user) throws Exception {
        String base = aiProps.getBaseUrl();
        String apiKey = System.getenv(aiProps.getApiKeyEnv());
        if (base == null || apiKey == null) {
            throw new IllegalStateException("AI base-url or API key env missing. Configure app.ai in application.yml and export API key env variable.");
        }
        String m = (model != null && !model.isBlank()) ? model : aiProps.getModel();

        // Chat Completions payload
        String url = base.endsWith("/") ? base + "chat/completions" : base + "/chat/completions";
        // Some providers (OpenAI) require /v1/chat/completions; if base already includes /v1, that's fine.

        String json = mapper.writeValueAsString(Map.of(
                "model", m,
                "messages", List.of(
                        Map.of("role", "system", "content", system),
                        Map.of("role", "user", "content", user)
                ),
                "temperature", 0.2
        ));

        RequestBody body = RequestBody.create(json, MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("AI request failed: HTTP " + response.code() + " - " + response.message());
            }
            String resp = response.body().string();
            // Try to parse JSON response generically
            Map<?,?> root = mapper.readValue(resp, Map.class);
            Object choices = root.get("choices");
            if (choices instanceof List && !((List<?>)choices).isEmpty()) {
                Object first = ((List<?>)choices).get(0);
                if (first instanceof Map) {
                    Object msg = ((Map<?,?>)first).get("message");
                    if (msg instanceof Map) {
                        Object content = ((Map<?,?>)msg).get("content");
                        return content != null ? content.toString() : resp;
                    }
                }
            }
            return resp;
        }
    }
}
